﻿using System.Security.Cryptography;
using System.Text;

namespace Scm.Jwt.Util
{
    public class StringUtil
    {
        public static string GetRandomStr(int Length, bool NeedSymbol = false,bool Lower = true)
        {
            string str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            if (NeedSymbol)
            {
                str += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; //复杂字符
            }
            StringBuilder sb = new();
            Random rd = new();
            for (int i = 0; i < Length; i++)
            {
                sb.Append(str.AsSpan(rd.Next(0, str.Length), 1));
            }

            if (Lower) return sb.ToString().ToLower();
            else return sb.ToString();
        }

        
        public static string GenJwtSecret()
        {
            var sb = new StringBuilder();
            sb.Append(GetRandomStr(8)).Append('-')
                .Append(GetRandomStr(4)).Append('-')
                .Append(GetRandomStr(4)).Append('-')
                .Append(GetRandomStr(4)).Append('-')
                .Append(GetRandomStr(12));
            return sb.ToString();
        }


        public static string MD5String(string encryptString,bool Lower = false)
        {
            byte[] result = Encoding.Default.GetBytes(encryptString);
            MD5 md5 = MD5.Create();
            byte[] output = md5.ComputeHash(result);
            string encryptResult = BitConverter.ToString(output).Replace("-", "");
            if(Lower) return encryptResult.ToLower();
            return encryptResult;
        }
    }
}
